package com.zengdada.dml.utils;

import com.alibaba.fastjson.JSONObject;
import com.zengdada.authority.utils.PublicSearchRangeAssist;
import com.zengdada.authority.utils.where.Where;
import com.zengdada.authority.utils.where.result.AnalysisResult;
import com.zengdada.authority.utils.where.result.AnalysisResultMerge;
import com.zengdada.dml.model.DmlColumnExtend;
import com.zengdada.dml.model.type.StaticSelect;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zsa
 * @date 2020/9/9 16:48
 * @description TODO
 */
public class DmlWhere extends Where {

    //    private void handleSearch(StaticSelect select, List<Where> filters) {
//        handleSearch(select, new Where(Formula.AND, filters));
//    }
//
//    private void handleSearch(StaticSelect select, Where where) {
//
//        if (where.isValid()) {
//            return;
//        }
//        // 是条件之间的关联关系 and / or
//        if (where.isRel()) {
//            String formula = where.getFormula();
//            List<Where> params = where.getParams();
//        }else {
//
//        }
//    }


    /**
     * dml
     */
    private StaticSelect select;

    public StaticSelect getSelect() {
        return select;
    }

    public DmlWhere setSelect(StaticSelect select) {
        this.select = select;
        return this;
    }

//    public void analysisLastResult(AnalysisResult result, AnalysisResult analysis) {
//        if (analysis != null && !analysis.isNull()) {
//            result.addAllParamValues(analysis.getParamValues());
//            result.addAllAnyWhereParamValues(analysis.getAnyWhereParamValues());
//            if (!analysis.getExtraFilters().isEmpty()) {
//                if (analysis.getExtraFilters().size() == 1) {
//                    result.addExtraFilter(analysis.getExtraFilters().get(0));
//                } else {
//                    result.addExtraFilter(String.format("( %s )", String.join(" " + analysis.getRel() + " ", analysis.getExtraFilters())));
//                }
//            }
//            if (!analysis.getAnyWhereExtraFilters().isEmpty()) {
//                if (analysis.getAnyWhereExtraFilters().size() == 1) {
//                    result.addAnyWhereExtraFilter(analysis.getAnyWhereExtraFilters().get(0));
//                } else {
//                    result.addAnyWhereExtraFilter(String.format("( %s )", String.join(" " + analysis.getRel() + " ", analysis.getAnyWhereExtraFilters())));
//                }
//            }
//        }
//    }

    public AnalysisResultMerge analysisMerge(StaticSelect select) {
        setSelect(select);
        return analysisMerge();
    }

    public AnalysisResultMerge analysisMerge() {
//        AnalysisResult result = new AnalysisResult();
//        AnalysisResult analysis = analysis();
//        analysisLastResult(result, analysis);
//        result.setRel(analysis.getRel());
        return new AnalysisResultMerge(analysis());
    }

    public AnalysisResult analysis(StaticSelect select) {
        setSelect(select);
        return analysis();
    }

    public AnalysisResult analysis() {
        if (select == null) {
            throw new RuntimeException("DmlWhere Dml（select） 必须存在");
        }
        if (!isValid()) {
            return null;
        }
        AnalysisResult result = new AnalysisResult();
        if (isRel()) {
            result.setRel(getFormula().toUpperCase());
//            List<String> extraFilters = new ArrayList<>(1);
//            List<String> anyWhereExtraFilters = new ArrayList<>(1);
            for (Where param : getParams()) {
                if(param == null) {
                    continue;
                }
                DmlWhere dmlWhere = JSONObject.parseObject(JSONObject.toJSONString(param), DmlWhere.class);
                dmlWhere.setSelect(select);
                AnalysisResultMerge analysisResultMerge = new AnalysisResultMerge(dmlWhere.analysis());
                result.addAnalysisResultMerge(analysisResultMerge);
            }
        } else {
            // 通过列名称找到该列
            DmlColumnExtend column = select.findColByLabel(getField());
            // 在预定列中没有查找到筛选列
            if (column == null) {
                return null;
            }
            // 列不具有可查询属性
            if (!column.hasAttr(DmlColumnExtend.ATTR_QUERYABLE)) {
                return null;
            }
            boolean anyWhere = column.getColumnType() == DmlColumnExtend.ANY_WHERE_COLUMN;
            Object val = getConditionVal();
            List<String> extraFilterContents = new ArrayList<>();
            if (val != null) {
                if (val instanceof List) {
                    ((List<Object>) val).forEach(i -> {
                        if (anyWhere) {
                            result.addAnyWhereParamValues(i);
                        } else {
                            result.addParamValue(i);
                        }
                        extraFilterContents.add("?");
                    });
                } else if (val instanceof PublicSearchRangeAssist) {
                    if (anyWhere) {
                        result.addAnyWhereParamValues(((PublicSearchRangeAssist) val).getFront());
                        result.addAnyWhereParamValues(((PublicSearchRangeAssist) val).getAfter());
                        result.addAnyWhereExtraFilter(String.format("%s ? AND ? %s", getConditionAndPrefix(column.getName()), getConditionSuffix()));
                    } else {
                        result.addParamValue(((PublicSearchRangeAssist) val).getFront());
                        result.addParamValue(((PublicSearchRangeAssist) val).getAfter());
                        result.addExtraFilter(String.format("%s ? AND ? %s", getConditionAndPrefix(column.getName()), getConditionSuffix()));
                    }
                    return result;
                } else {
                    if (anyWhere) {
                        result.addAnyWhereParamValues(val);
                    } else {
                        result.addParamValue(val);
                    }
                    extraFilterContents.add("?");
                }
            }
            String sql = String.format("%s %s %s", getConditionAndPrefix(column.getName()), String.join(", ", extraFilterContents), getConditionSuffix());
            if (anyWhere) {
                result.addAnyWhereExtraFilter(sql);
            } else {
                result.addExtraFilter(sql);
            }
        }
        return result;
    }


    public static void main(String[] args) {
        DmlWhere dmlWhere = new DmlWhere();
        dmlWhere.setFormulaE(Formula.AND);
        dmlWhere.setParams(new ArrayList<Where>() {{
            add(new Where("name", "aaa"));
            add(new Where("name1", "aaa1"));
            add(new Where("age", "10"));
            add(new Where(Formula.OR, new ArrayList<Where>() {{
                add(new Where("age", Formula.RANGE, "9~~10"));
                add(new Where("name", "aaa"));
            }}));
        }});
        StaticSelect select = new StaticSelect();
        select.add("name", "", String.class);
        select.add("name1", "", String.class);
        select.add("age", "", String.class);
        List<DmlColumnExtend> columns = select.getColumns();
        for (DmlColumnExtend column : columns) {
            column.setAttr(32, true);
        }
        columns.get(1).setColumnType(-1);
        dmlWhere.setSelect(select);
        AnalysisResult analysis = dmlWhere.analysis();

        if (!analysis.getExtraFilters().isEmpty()) {
            System.out.println("ExtraFilters   --  " + String.format("( %s )", String.join(" " + analysis.getRel() + " ", analysis.getExtraFilters())));
        }
        if (!analysis.getAnyWhereExtraFilters().isEmpty()) {
            System.out.println("AnyWhereExtraFilters   --  " + String.format("( %s )", String.join(" " + analysis.getRel() + " ", analysis.getAnyWhereExtraFilters())));
        }
        System.out.println();
    }
}
